// mycomponent/multistageTab/multistageTab.js
const app = getApp();
const height = wx.getSystemInfoSync().windowHeight;
// import tool from "../../utils/util"
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
    bottomShowBol: {
      type: null,
    },
    bottomShowBolIndex: {
      type: null,
    },
    index: {
      type: null,
    },
    btnFlag: {
      type: null,
    },
    page_id: {
      type: null,
    },
    store_id: {
      type: null
    }
    // scrtop: {
    //   type: null,
    // }
  },
  observers: {
    btnFlag: function (btn) {
      // console.log(btn, '111');
    },
    // scrtop: function (top) {
    // this.setData({
    //   thrScrtop:
    // })
    // this.methodDragend();
    // }
  },
  lifetimes: {
    attached: function () {
      if (this.data.bottomShowBolIndex == this.data.index) {
        setTimeout(() => {
          this.setData({
            showTabs: true
          });
          // 延迟显示防止置顶
        }, 200);
      }
      let arr = this.data.datas.list;
      let infoDatas = [];
      let navDatas = [];
      arr.forEach((element) => {
        navDatas.push(element.second_list);
        if (element.second_list[0]) {
          infoDatas.push(element.second_list[0].components);
        } else {
          infoDatas.push([]);
        }
      });
      let allDatas = [];
      navDatas.forEach((element, k) => {
        // if (element.length > 6 && this.data.datas.show_first_tab) {
        //   element = element.slice(0, 7);
        // }
        element.forEach((el, i) => {
          if (i == 0) {
            el.tabSelectShow = el.id;
          }
        });
        allDatas.push(element);
      });
      this.setData({
        infoDatas: infoDatas,
        // navDatas:navDatas,
        allDatas: allDatas,
      });
      // console.log(infoDatas, allDatas);
      // console.log(this.data.datas, allDatas);
      // 在组件实例进入页面节点树时执行

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  ready() {

  },

  /**
   * 组件的初始数据
   */
  data: {
    intoSelect: 0,
    leftScrollTop: 0,
    rightScrollTop: 0,
    infoDatas: [], //商品组数组
    navDatas: [], //二级导航数组
    showTabs: false,
    leftPosShow: false,
    isFixedArr: [],
    isLeftFixed: false,
    listHeight: [],
    childPos: false,

    height: height,
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 换一换
    async tapChange(e) {
      let all = e.currentTarget.dataset.all;
      let index = e.currentTarget.dataset.index;
      let second_list = this.data.datas.list[index].second_list;
      let allDatas = all;
      let lastInd = allDatas.length - 1;
      let lastIndId = allDatas[allDatas.length - 1].id;
      let isLast = await this.tapchangeOne(lastInd, second_list, lastIndId);
      let arr;
      if (typeof isLast == "object") {
        arr = second_list.slice(isLast.ind, isLast.listinid);
      }
      for (let index = 0; index < arr.length; index++) {
        arr[index].tabSelectShow = isLast.tabShow;
      }
      this.setData({
        ["allDatas[" + index + "]"]: arr,
      });
      console.log(this.data.allDatas);
    },
    tapchangeOne(lastInd, second_list, lastIndId) {
      return new Promise((resove, reject) => {
        let listinid = second_list.length - 1;
        let tabShow;
        second_list.forEach((element, i) => {
          if(element.tabSelectShow){
            tabShow = element.tabSelectShow;
          }
          if (element.id == lastIndId) {
            if (i == listinid) {
              let objind = {
                ind: 0,
                listinid: 7,
                tabShow
              };
              resove(objind);
            }
            if (listinid - i >= 8) {
              let objind = {
                ind: lastInd,
                listinid: lastInd + 8,
                tabShow
              };
              resove(objind);
            } else {
              let objind = {
                ind: i,
                listinid: listinid + 1,
                tabShow
              };
              resove(objind);
            }
          }
        });
      });
    },
    tapClassDivGetind(datasinfo, allinfo) {
      return new Promise((resove, reject) => {
        datasinfo.forEach((element, i) => {
          if (element.id == allinfo) {
            let json = {
              key: i,
              info: element
            };
            resove(json);
          }
        });
      });
    },
    // 切换二级分类
    async tapClassDiv(e) {
      let ind = e.currentTarget.dataset.ind;
      let index = e.currentTarget.dataset.index;
      let all = e.currentTarget.dataset.all;
      let datasinfo = this.data.datas.list[index].second_list;
      let allinfo = all[ind].id;
      datasinfo.forEach((element, i) => {
        element.tabSelectShow = '';
        if (element.id == allinfo) {
          element.tabSelectShow = element.id;
        }
      });
      this.setData({
        ["infoDatas[" + index + "]"]: all[ind].components,
        ["allDatas[" + index + "]"]: this.data.allDatas[index],
        ["datas.list["+index+"].second_list"]:datasinfo,
        bz: `a${index}`,
      });
      let indexListTap = await this.tapClassDivGetind(datasinfo, allinfo);
      let component = indexListTap.info.components;
      let componentKeyInd = indexListTap.key;
      if (component.length == 0) {
        let heightLi = await this.updateHeight();
        this.setData({
          listHeight: heightLi
        });
      }

      for (let i = 0; i < component.length; i++) {
        if (component[i].uikey == "U_goods") {
          let json = {
            page: 1,
            decorate_id: this.data.page_id,
            component_id: this.data.component_id,
            component_key: "U_moretabcontrol",
          };
          json.component_info = {
            list_key: index,
            second_list_key: componentKeyInd,
            components_key: i,
          };
          json.component_info = JSON.stringify(json.component_info);
          wx.showLoading({
            title: '加载中',
            icon: 'none'
          });
          await this.tapClassGet(json, index, ind, i);
          wx.hideLoading({
            success: (res) => {},
          });
          let heightLi = await this.updateHeight();
          this.setData({
            listHeight: heightLi
          });
        } else {
          this.setData({
            rightScrollTop: this.data.listHeight[index] + 10
          });
        }
      }
    },
    // 切换二级导航
    tapClassGet(json, index, ind, i) {
      return new Promise((resove, reject) => {
        const goodsListC = this.selectComponent(`#goodsListC${index}`);
        let urlStr = app.getNetAddresss("home-page.get-decorate-page");
        if(this.properties.store_id) urlStr += `&store_id=${this.properties.store_id}`;
        app._getNetWork({
          url: urlStr,
          data: json,
          success: (resdata) => {
            if(resdata.data.result == 1){
              if(this.data.infoDatas[index][i]){
                this.setData({
                  ['infoDatas[' + index + '][' + i + '].remote_data.list']: resdata.data.data,
                  rightScrollTop: this.data.listHeight[index] + 10
                });
                goodsListC.tabTwoContro(this.data.infoDatas[index][i].remote_data.list,index);
              }
            }
            resove();
          },
          fail: (res) => {
            console.log(res);
            wx.showToast({
              title: res.msg,
              icon: 'none'
            });
            wx.hideLoading({
              success: (res) => {},
            });
          },
        });
      });
    },
    onReadEnd(e){
        let index = e.detail.index;
        const query = this.createSelectorQuery()
        query.select(`#goodsListC${index}`).boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function(res){
          console.log(res[0],res[1])
          if(res[0].top == 0) return
          let top = 0;
          if(res[1].scrollTop > res[0].top){
            if(res[0].top < 0){
              top = (res[1].scrollTop + res[0].top) -70 
            }else{
              return
            }
          }else{
            top = res[0].top
          }
          wx.pageScrollTo({
            scrollTop:top,
            complete:function(e){
              console.log(e)
            }
          })
        })
    },
    // 左侧一级导航点击
    tapIntoSelect(e) {
      let ind = `a${e.currentTarget.dataset.ind}`;
      this.createSelectorQuery()
        .selectViewport().scrollOffset()
        .select(`#${ind}`)
        .boundingClientRect()
        .exec((res) => {
          // console.log(res[0].scrollTop + res[1].top, '点击ssssss2', '当前页面滚动条位置', )
          wx.pageScrollTo({
            scrollTop: res[0].scrollTop + res[1].top + 20,
            duration: 500,
          });
          this.setData({
            intoSelect:e.currentTarget.dataset.ind
          })
        });
    },
    // ondisplay(evt) {
    //   let index = evt.detail.index;
    //   let display = evt.detail.display;
    //   console.log(index,display,'ondisplay')
    //   if (!display) {
    //     this.setData({
    //       intoSelect: index,
    //     });
    //   } else if (index == this.data.intoSelect) {
    //     this.setData({
    //       intoSelect: null,
    //     });
    //   }
    // },
    ondisplayListView1(evt) {
      let index = evt.detail.index;
      let display = evt.detail.display;
      let type = evt.detail.type;
      let list = this.data.datas.list;
      if (type == 'up') {
        if (display) {
          list[index].childPos = false;
        } else {
          list[index].childPos = true;
        }
      } else {
        list[index].childPos = false;
      }
      this.setData({
        ['datas.list']: list
      });
    },
    ondisplayListView(evt) {
      let index = evt.detail.index;
      let display = evt.detail.display;
      let type = evt.detail.type;
      this.getLeftHight(this.data.intoSelect);
      // if(!display && index==this.data.intoSelect){
      //   this.setData({
      //     intoSelect: null,
      //    })
      // }else if(display && this.data.intoSelect==null ) {
      //   this.setData({
      //     intoSelect: index,
      //    })
      // }
      if (display && type == 'up') {
        this.setData({
          intoSelect: index,
        });
      } else if (type == 'up') {
        this.setData({
          intoSelect: (index + 1)
        });

      }
    },
    // 二级菜单监听
    onscroll(e) {
      // console.log(e.currentTarget.dataset.index, e.detail.isFixed,'11111111')
      // let index = e.currentTarget.dataset.index;
      // console.log(this.data.isFixedArr,index)
      // if(e.detail.isFixed) {
      //   if(this.data.isFixedArr.indexOf(index)==-1) {
      //     this.data.isFixedArr.push(index);
      //   }
      // }else {
      //   this.data.isFixedArr = this.data.isFixedArr.filter((item)=>{return item != index});
      // }
      // index = Math.max.apply(null,this.data.isFixedArr);
      // if(this.data.intoSelect != index) {
      //   this.setData({
      //    intoSelect: index,
      //   })
      //   // console.log(this.data.intoSelect)
      // }
    },
    // 左边导航监听
    onLeftscroll(e) {
      if (e.detail.isFixed) {
        if (!this.data.isLeftFixed) {
          this.setData({
            isLeftFixed: e.detail.isFixed
          });
        }
      } else {
        if (this.data.isLeftFixed) {
          this.setData({
            isLeftFixed: e.detail.isFixed
          });
        }
      }
    },
    bindscroll(e) {
      let intoSelect = this.checkarr(e.detail.scrollTop, this.data.listHeight);
      if (this.data.intoSelect != intoSelect) {
        this.setData({
          intoSelect: intoSelect
        });
      }
      console.log(e.detail.scrollTop, this.data.intoSelect);
    },
    checkarr(Top, min) {
      let ind;
      for (let i = 0; i < min.length; i++) {
        if (Top >= (min[i]) && Top < min[i + 1]) {
          ind = i;
        }
      }
      if (Top >= (min[ind] + 50) && Top < (min[ind + 1] - 100)) {
        if (!this.data.childPos) {
          this.setData({
            childPos: true
          });
        }
      } else if (Top < 50) {
        if (this.data.childPos) {
          this.setData({
            childPos: false
          });
        }
      } else {
        if (this.data.childPos) {
          this.setData({
            childPos: false
          });
        }
      }
      return ind;
    },
    resultMrh(tops) {
      let ind = "";
      for (let i = 0; i < this.data.datas.list.length; i++) {
        if (tops[i].top <= 0) {
          ind = i;
        }
      }
      return String(ind);
    },
    setIntoselect(intoSelect) {
      if (Object.prototype.toString.call(intoSelect) !== '[object Object]') {
        this.setData({
          intoSelect: intoSelect
        });
      } else {
        this.setData({
          intoSelect: 0
        });
      }
      console.log(intoSelect, "intoSelect", Object.prototype.toString.call(intoSelect) === '[object Object]', this.data.intoSelect);
    },
    imgload(evt) {
      // console.log("加载完成",evt)
      this.methodDragend();
    },
    updateHeight() {
      return new Promise((resove, reject) => {
        const query = this.createSelectorQuery();
        query.selectAll(".rightScrollViewNode").boundingClientRect();
        query.exec((res) => {
          let resAll = res[0];
          let height = 0;
          this.data.listHeight = [0];
          resAll.map((item) => {
            height += item.height;
            this.data.listHeight.push(height);
          });
          resove(this.data.listHeight);
          return;
        });
      });
    },
    methodDragend(e) {
      const query = this.createSelectorQuery();
      query.selectAll(".rightScrollViewNode").boundingClientRect();
      query.exec((res) => {
        let resAll = res[0];
        let height = 0;
        this.data.listHeight = [0];
        resAll.map((item) => {
          height += item.height;
          this.data.listHeight.push(height);
        });
        this.setData({
          listHeight: this.data.listHeight
        });
        return;
      });
    },

    //左边监听高度（
    leftPos() {
      this.createSelectorQuery()
        .selectAll("#tabNode")
        .boundingClientRect()
        .exec((res) => {
          if (res[0][0].top <= 0) {
            if (Math.abs(res[0][0].top) <= 30) {
              if (this.data.leftPosShow) {
                this.setData({
                  leftPosShow: false
                });
              }
              return;
            }
            if (!this.data.leftPosShow) {
              this.setData({
                leftPosShow: true
              });
            }

          } else {
            // if(this.data.leftPosShow) {
            //  this.setData({
            //    leftPosShow: false
            //  })
            // }
          }
        });
    },
    //右边滑动距离显示置顶效果
    getRightFiexd(ind, resAll) {
      // 子元素高度
      let minOffsetHeight = resAll[ind].height;
      // 元素滚动距离
      let minRectHeight = Math.abs(resAll[ind].top);
      console.log('子元素高度', minOffsetHeight);
      console.log('元素滚动距离', minRectHeight);

      if (minRectHeight < 114) {
        console.log('xxxxxxxxxxxxxxxx11');
        return false;
      }
      if (minRectHeight >= 114 && minRectHeight <= minOffsetHeight - 300) {
        console.log('xxxxxxxxxxxxxxxx22');
        return true;
      }
    },
    //联动左边滚动条
    getLeftHight(ind) {
      this.createSelectorQuery()
        .selectAll(".leftinto")
        .boundingClientRect()
        .exec((res) => {
          let resAll = res[0];
          if (ind == this.data.intoSelect) {
            return;
          }
          if (ind <= 4) {
            // 保持左边滚动位置为0
            this.setData({
              leftScrollTop: 0,
            });
            return;
          }
          if (resAll[this.data.intoSelect]) {
            this.setData({
              leftScrollTop: resAll[this.data.intoSelect].height * ind - 130,
            });
          }
        });
    },
  },
});